import json
from pathlib import Path
from typing import List
from .data_models import CaseData, ClassificationCode
import re  # 需要添加这一行，因为在ClassificationCode中使用了re模块

_CASES_DATA = None

def load_cases() -> List[CaseData]:
    """加载并验证案例数据"""
    global _CASES_DATA
    if _CASES_DATA is None:
        data_path = Path(__file__).parent / 'cases.json'
        
        with open(data_path, 'r', encoding='utf-8') as f:
            raw_data = json.load(f)
        
        # 数据转换
        processed = []
        for case in raw_data:
            # 转换正确分类
            case['正确分类'] = {k: ClassificationCode(code=v[0], name=v[1]) 
                            for k, v in case['正确分类'].items()}
            
            # 转换常见误判 - 这是一个嵌套列表
            processed_misclassifications = {}
            for category, misclassifications in case['常见误判'].items():
                processed_misclassifications[category] = [
                    ClassificationCode(code=code, name=name) 
                    for code, name in misclassifications
                ]
            case['常见误判'] = processed_misclassifications
            
            processed.append(CaseData(**case))
        
        _CASES_DATA = processed
    return _CASES_DATA

def get_case_names() -> List[str]:
    """获取所有案例名称"""
    return [case.案例名称 for case in load_cases()]
